package arg

import (
	"encoding/json"
	"fmt"
	"github.com/gurkankaymak/hocon"
	"db2s/global"
	"reflect"
	"strings"
	"time"
)

type dbPoolLevel struct {
	MaxOpenConn     int `json:"maxOpenConn"`
	MaxIdleConn     int `json:"maxIdleConn"`
	ConnMaxIdleTime int `json:"connMaxIdleTime"`
	ConnMaxLifeTime int `json:"connMaxLifeTime"`
}

// dbpool parameter Check
func dbPoolSecondaryLevelParameter(dbPool hocon.Object) (DbPool DBPool, err error) {
	var (
		dbPoolMap map[string]any
	)
	var s2 []string
	if dbPoolMap, err = global.StructToMapAny(getDbPool()); err != nil {
		return
	}
	for k, v := range dbPoolMap {
		if r1 := rc.getHoconConfigVal(dbPool.ToConfig(), k, reflect.TypeOf(v).String()); r1 != nil {
			s2 = append(s2, rc.anyToJsonString(k, r1))
		} else {
			s2 = append(s2, rc.anyToJsonString(k, v))
		}
	}
	if err = json.Unmarshal([]byte(fmt.Sprintf("{%s}", strings.Join(s2, ","))), &DbPool); err != nil {
		fmt.Println(err)
	}
	DbPool.ConnMaxLifeTime = DbPool.ConnMaxLifeTime * time.Second
	DbPool.ConnMaxIdleTime = DbPool.ConnMaxIdleTime * time.Second
	//rc.SecondaryL.DBPoolV.ConnMaxLifeTime = rc.SecondaryL.DBPoolV.ConnMaxLifeTime * time.Second
	//rc.SecondaryL.DBPoolV.ConnMaxIdleTime = rc.SecondaryL.DBPoolV.ConnMaxIdleTime * time.Second
	return
}

type DbPoolModeCheck struct {
	FunctionalMode    []string       `json:"funcMode"`
	FuncPassParameter map[string]any `json:"funcPass"`
}

// dbPoolParameterCheck
func dbPoolParameterCheck(p *SecondaryLevel, s DbPoolModeCheck) (err error) {
	var (
		schemaMap map[string]any
	)
	if schemaMap, err = global.StructToMapAny(s); err != nil {
		return err
	} else {
		if v, ok := schemaMap["funcMode"]; ok {
			var funcExist bool
			for _, v1 := range v.([]string) {
				if strings.EqualFold(p.FunctionalMode, v1) {
					funcExist = true
				}
			}
			if !funcExist {
				return nil
			}
		}
	}
	if p.DBPoolV.MaxOpenConn < 1 {
		//global.Wlog.Debug(fmt.Sprintf("(%v) %v The current parameter %s configuration error will use the default value {%v}", LogThreadSeq, Event, "maxOpenConn", 100))
		rc.SecondaryL.DBPoolV.MaxOpenConn = 100
	}
	if p.DBPoolV.MaxIdleConn < 1 {
		//global.Wlog.Debug(fmt.Sprintf("(%v) %v The current parameter %s configuration error will use the default value {%v}", LogThreadSeq, Event, "maxIdleConn", 50))
		p.DBPoolV.MaxIdleConn = 50
	}
	if p.DBPoolV.ConnMaxIdleTime < 1 {
		//global.Wlog.Debug(fmt.Sprintf("(%v) %v The current parameter %s configuration error will use the default value {%v}", LogThreadSeq, Event, "connMaxIdleTime", 500))
		p.DBPoolV.ConnMaxIdleTime = 500
	}
	if p.DBPoolV.ConnMaxLifeTime < 1 {
		//global.Wlog.Debug(fmt.Sprintf("(%v) %v The current parameter %s configuration error will use the default value {%v}", LogThreadSeq, Event, "connMaxLifeTime", 1000))
		p.DBPoolV.ConnMaxLifeTime = 1000
	}
	return
}
